package com.atguigu.lease.admin.service.impl;

import com.atguigu.lease.model.dto.AgreementQueryDto;
import com.atguigu.lease.model.vo.AgreementItemVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.bean.LeaseAgreement;
import com.atguigu.lease.admin.service.LeaseAgreementService;
import com.atguigu.lease.admin.mapper.LeaseAgreementMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author 1
* @description 针对表【lease_agreement(租约信息表)】的数据库操作Service实现
* @createDate 2025-09-22 17:18:51
*/
@Service
public class LeaseAgreementServiceImpl extends ServiceImpl<LeaseAgreementMapper, LeaseAgreement>
    implements LeaseAgreementService{

    @Override
    public Page<AgreementItemVo> getPage(AgreementQueryDto queryDto) {
        //自定义sql查询
        return baseMapper.selectAgreementItemVoPage(new Page<AgreementItemVo>(queryDto.getCurrent(), queryDto.getSize())
                , queryDto);
    }

    @Override
    public AgreementItemVo getAgreementItemVoById(Long id) {

        return baseMapper.selectAgreementItemVoById(id);
    }

    @Override
    public void saveOrUpdateLeaseAgreement(LeaseAgreement leaseAgreement) {
        //1、校验 本次要租的房间 是否存在有效的租约
        // 查询 不是本次租房用户的 并且有效的 这个房间的租约信息
        //where room_id = 3 and status in(2,5) and identi_num != xxx
        long count = super.count(Wrappers.lambdaQuery(LeaseAgreement.class)
                .eq(LeaseAgreement::getRoomId, leaseAgreement.getRoomId())
                .in(LeaseAgreement::getStatus, 2, 5)
                .ne(LeaseAgreement::getIdentificationNumber, leaseAgreement.getIdentificationNumber())
        );
        if(count > 0) {
            //房间 被其他人租走了，租约有效
            throw new RuntimeException("手太慢了，房间已经被租出去了");
        }
        //2、保存或更新租约
        saveOrUpdate(leaseAgreement);
    }
}




